<template>
  <div>
    <div style="margin-top: 3%;">
      <el-form :inline="true" ref="form" label-width="100px">
        <!-- <el-form-item label="表单名称">
          <el-select v-model="searchParams.resourceTypeTbale" placeholder="请选择资表单名称" @change="handleResourceTypeChange">
            <el-option label="新区云平台硬件台账" value="gzclybz"></el-option>
            <el-option label="新区云平台硬件检修台账" value="Yjjxybz"></el-option>
          </el-select>
        </el-form-item> -->

        <el-form-item label="全局搜索">
          <el-input placeholder="请输入关键字名称" v-model="searchParams.resource_name"></el-input>
        </el-form-item>


        <el-form-item label="处置时间">
          <el-date-picker v-model="searchParams.startDate" type="date" placeholder="开始日期" style="width: 140px;"
            value-format="yyyy-MM-dd"></el-date-picker>
          <span style="margin: 0 5px;">-</span>
          <el-date-picker v-model="searchParams.endDate" type="date" placeholder="结束日期" style="width: 140px;"
            value-format="yyyy-MM-dd"></el-date-picker>
        </el-form-item>


        <el-form-item>
          <el-button @click="resetAndFetchData">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleCreate">新建</el-button>
        </el-form-item>
        <el-button @click="exportAllToExcel">导出数据</el-button>
      </el-form>
    </div>

    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" @before-close="closeDialog">
      <el-form :label-position="'left'" label-width="120px" :model="formData" :rules="formRules" ref="form">
        <!-- 动态渲染表单字段 -->
        <template v-if="searchParams.resourceTypeTbale === 'Gzclybz'">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="处理人" prop="handler">
                <el-input v-model="formData.handler" style="width: 100%;" placeholder="处理人"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="故障名称" prop="fault_name">
                <el-input v-model="formData.fault_name" style="width: 100%;" placeholder="故障名称"></el-input>
              </el-form-item>
            </el-col>
          </el-row> 
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="业务系统名称" prop="business_system_name">
                <el-input v-model="formData.business_system_name" style="width: 100%;" placeholder="业务系统名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发生时间" prop="occurred_at">
                <el-date-picker type="date" placeholder="发生时间" v-model="formData.occurred_at" style="width: 100%;"
                  value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="处置时间" prop="resolution_time">
                <el-date-picker type="date" placeholder="处置时间" v-model="formData.resolution_time" style="width: 100%;"
                  value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="数据库问题类型" prop="db_issue_type">
                <el-input v-model="formData.db_issue_type" style="width: 100%;" placeholder="数据库问题类型"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="故障产生原因" prop="cause_of_fault">
                <el-input v-model="formData.cause_of_fault" style="width: 100%;" placeholder="故障产生原因"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="处理方法" prop="resolution_method">
                <el-input v-model="formData.resolution_method" style="width: 100%;" placeholder="处理方法"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="业务侧是否有反馈" prop="has_business_feedback">
                <el-input v-model="formData.has_business_feedback" style="width: 100%;"
                  placeholder="业务侧是否有反馈"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="处置结果" prop="resolution_result">
                <el-input v-model="formData.resolution_result" style="width: 100%;" placeholder="处置结果"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="业务侧反馈的整改时间" prop="business_rectification_time">
                <el-date-picker type="date" placeholder="业务侧反馈的整改时间" v-model="formData.business_rectification_time"
                  style="width: 100%;" value-format="yyyy-MM-dd"></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否重复出现" prop="is_repeated">
                <el-input v-model="formData.is_repeated" style="width: 100%;" placeholder="是否重复出现"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="备注" prop="remarks">
                <el-input v-model="formData.remarks" style="width: 100%;" placeholder="备注"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetForm">重置</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">提交</el-button>
      </span>
    </el-dialog>

    <div style="margin: 2%;width: 96%; overflow-x: auto;">
      <el-table :data="listData" border :style="tableStyle">
        <el-table-column v-for="column in displayedColumns" :key="column.prop" :prop="column.prop" :label="column.label"
          v-if="column.visible && column.prop !== 'operation'" :show-overflow-tooltip="true"
          :min-width="column.minWidth || '150px'" :max-width="column.maxWidth" sortable>
        </el-table-column>
        <!-- 操作列特殊处理，始终保持显示 -->
        <el-table-column label="操作" :min-width="'150px'" fixed="right">
          <template slot-scope="scope">
            <el-button size="mini" @click="edit(scope.row)">编辑</el-button>
            <el-button size="mini" type="danger" @click="DeleteInfo(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="bottom-pagination">
      <el-pagination style="margin: 30px 0px;" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="currentPage" :page-sizes="[10, 20, 50, 100]" :page-size="perPage"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>
  </div>
</template>

<script>

import axios from 'axios';
import * as XLSX from 'xlsx';
import { saveAs } from 'file-saver';

export default {
  data() {
    return {
      listData: [], // 存储列表数据
      searchParams: {
        //  name: '', // 名称搜索参数
        resource_name: '', // 模糊搜索关键字
        resourceTypeTbale: 'Gzclybz', // 设置默认值
        startDate: '',
        endDate: '',
      },
      currentPage: 1, // 当前页码
      perPage: 10, // 每页数量
      total: 0, // 总条数
      displayedColumns: [], // 动态设置表格列
      //新建表单相关参数
      dialogVisible: false,
      //编辑对话框
      dialogTitle: '新增数据', // 根据场景动态改变
      isCreating: true, // 新增时为true，编辑时为false

      resourceTypeTbale: 'Gzclybz',
      dialogTitle: '',
      formData: {},
      formRules: {
        // 定义表单验证规则
        handler: [
          { required: true, message: '处理人不能为空', trigger: 'change' }
        ],
        fault_name: [
          { required: true, message: '故障名称不能为空', trigger: 'change' }
        ],
        occurred_at: [
          { required: true, message: '发生时间不能为空', trigger: 'change' }
        ],
        business_system_name: [
          { required: true, message: '业务系统名称不能为空', trigger: 'change' }
        ],
        db_issue_type: [
          { required: true, message: '数据库问题类型不能为空', trigger: 'change' }
        ],
        cause_of_fault: [
          { required: true, message: '处理方法不能为空', trigger: 'change' }
        ],
        resolution_time: [
          { required: true, message: '处置时间不能为空', trigger: 'change' }
        ],
        has_business_feedback: [
          { required: true, message: '业务侧是否有反馈不能为空', trigger: 'change' }
        ],
        resolution_result: [
          { required: true, message: '处置结果不能为空', trigger: 'change' }
        ],
        business_rectification_time: [
          { required: true, message: '业务侧反馈的整改时间不能为空', trigger: 'change' }
        ],
        is_repeated: [
          { required: true, message: '是否重复出现不能为空', trigger: 'change' }
        ],
      },
      tableStyle: {
        width: '100%',
        tableLayout: 'auto',
      },
    };
  },

  methods: {
    fetchData() {
      axios.get('/api/gzclybz/search_ybz', {
        params: {
          //   name: this.searchParams.name,
          resource_name: this.searchParams.resource_name,
          resourceTypeTbale: this.searchParams.resourceTypeTbale,
          endDate: this.searchParams.endDate,
          startDate: this.searchParams.startDate,
          page: this.currentPage,
          per_page: this.perPage,
        }
      }).then(response => {
        this.listData = response.data.data;
        this.total = response.data.meta.total || 0; // 确保total有默认值
      }).catch(error => {
        console.error("Error fetching data:", error);
      });
    },
    //编辑
    edit(row) {
      this.dialogTitle = '编辑数据'; // 更改对话框标题
      this.isCreating = false; // 设置为编辑模式
      this.formData = { ...row }; // 填充表单数据，深拷贝避免引用问题
      this.dialogVisible = true; // 显示对话框
    },

    DeleteInfo(row) {
      console.log('Row Data:', row);
      this.showConfirmDeleteDialog(row);
    },

    // 新增方法：显示确认删除对话框
    showConfirmDeleteDialog(row) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 用户点击确定，执行删除操作
        this.deleteData(row);
      }).catch(() => {
        // 用户点击取消，不执行任何操作
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },

    // 删除数据的方法
    async deleteData(row) {
      try {
        // 调用后端删除API
        axios.delete(`/api/gzclybz/ybzDelete`, {
          params: {
            resourceTypeTbale: this.searchParams.resourceTypeTbale,
            id: row.id
          }
        }); // 假设row.id是需要删除的数据的ID
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        // 刷新表格数据，具体实现取决于你的数据获取和更新逻辑
        this.fetchData(); // 假设这是你用来刷新列表数据的方法
      } catch (error) {
        console.error('删除失败:', error);
        this.$message.error('删除失败，请重试！');
      }
    },

    //新建表单相关设置
    handleCreate() {
      this.resourceTypeTbale = this.searchParams.resourceTypeTbale; // 根据你的逻辑设置不同的类型
      this.dialogTitle = '新增数据';
      this.formData = {}; // 重置表单数据
      this.isCreating = true;
      this.dialogVisible = true;
    },

    //编辑功能
    submitForm() {
      this.$refs['form'].validate((valid) => { // 验证表单
        if (valid) {
          console.log(this.isCreating);
          if (this.isCreating) {
            // 发送 POST 请求到后端 API
            axios.post('/api/gzclybz/ybzCurd', {
              resourceTypeTbale: this.resourceTypeTbale,
              ...this.formData
            }).then(response => {
              this.dialogVisible = false;
              // 处理成功响应
              this.$message({
                message: '资源创建成功',
                type: 'success'
              });
            }).catch(error => {
              // 处理错误响应
              this.$message({
                message: '创建资源失败: ' + error.response.data.message,
                type: 'error'
              });
            });
          } else {
            axios.put(`/api/gzclybz/ybzEdit`, {
              resourceTypeTbale: this.searchParams.resourceTypeTbale,
              ...this.formData
            }, this.formData)
              .then(response => {
                this.$message.success('编辑成功');
                this.dialogVisible = false; // 关闭对话框
                this.fetchData(); // 刷新数据列表
              })
              .catch(error => {
                this.$message.error('编辑失败');
                console.error('编辑请求出错:', error);
              });
          }
        } else {
          return false;
        }
      });
    },

    //关闭编辑对话框
    closeDialog() {
      this.dialogVisible = false;
      this.formData = {}; // 重置表单数据
      this.isCreating = true; // 重置为新增模式
      // 其他可能需要的清理操作
    },

    //----------------分页相关
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    handleSizeChange(size) {
      this.perPage = size;
      this.currentPage = 1;
      this.fetchData();
    },
    resetSearch() {
      const currentResourceType = this.searchParams.resourceTypeTbale; // 保存当前的 resourceTypeTbale
      // this.searchParams = { name: '', resource_name: '', resourceTypeTbale: currentResourceType};
      this.searchParams = { resource_name: '', resourceTypeTbale: currentResourceType, startDate: '', endDate: '' };
      this.currentPage = 1;
      this.fetchData();
    },
    resetForm() {
      this.$refs.form.resetFields();
    },
    resetAndFetchData() {
      // 重置分页参数并重新查询
      this.currentPage = 1;
      this.fetchData();
    },

    clearAllFormData() {
      // 假设formData包含所有表单项数据
      const defaultValues = {}; // 定义一个对象来存储各字段的默认值，如果需要特定的默认值可在此定义
      for (const key in this.formData) {
        if (this.formData.hasOwnProperty(key)) {
          // 根据字段类型设置合理的默认值
          // 这里简单地设置为空字符串，根据实际情况调整
          this.formData[key] = typeof this.formData[key] === 'string' ? '' : null;
          // 或者使用预定义的默认值
          // this.formData[key] = defaultValues[key] || '';
        }
      }
    },
    handleResourceTypeChange() {
      this.searchParams.resource_name = '';
      this.currentPage = 1;
      this.updateColumns();
      this.fetchData(); // 请求后端数据
      this.clearAllFormData();
    },
    updateColumns() {
      const resourceType = this.searchParams.resourceTypeTbale;
      this.availableColumns = [
        { prop: 'handler', label: '处理人' },
        { prop: 'fault_name', label: '故障名称' },
        { prop: 'occurred_at', label: '发生时间' },
        { prop: 'business_system_name', label: '业务系统名称' },
        { prop: 'db_issue_type', label: '数据库问题类型' },
        { prop: 'cause_of_fault', label: '故障产生原因' },
        { prop: 'resolution_method', label: '处理方法' },
        { prop: 'resolution_time', label: '处置时间' },
        { prop: 'has_business_feedback', label: '业务侧是否有反馈' },
        { prop: 'resolution_result', label: '处置结果' },
        { prop: 'business_rectification_time', label: '业务侧反馈的整改时间' },
        { prop: 'is_repeated', label: '是否重复出现' },
        { prop: 'remarks', label: '备注' },
      ];
      this.displayedColumns = this.availableColumns.map(column => ({ ...column, visible: true }));
    },

    init() {
      this.updateColumns();
      this.fetchData();
    },
    exportAllToExcel() {
      axios.get('/api/gzclybz/search_ybz', {
        params: {
          //name: this.searchParams.name,
          resource_name: this.searchParams.resource_name,
          resourceTypeTbale: this.searchParams.resourceTypeTbale,
          // 请求所有数据
          page: 1,
          per_page: this.total,
        }
      }).then(response => {
        const allData = response.data.data;

        // 构建表头
        const headers = this.displayedColumns.filter(column => column.visible).map(column => column.label);
        const props = this.displayedColumns.filter(column => column.visible).map(column => column.prop);

        // 构建数据
        const data = allData.map(row => props.map(prop => row[prop]));

        // 添加表头到数据
        data.unshift(headers);

        // 创建工作簿
        const worksheet = XLSX.utils.aoa_to_sheet(data);
        const workbook = XLSX.utils.book_new();
        XLSX.utils.book_append_sheet(workbook, worksheet, 'Sheet1');

        // 导出 Excel 文件
        const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'array' });
        saveAs(new Blob([wbout], { type: 'application/octet-stream' }), '导出数据.xlsx');
      }).catch(error => {
        console.error("Error fetching all data:", error);
      });
    }
  },
  mounted() {
    this.init();
  }
};


</script>

<style>
.bottom-pagination {
  width: 100%;
  display: flex;
  justify-content: center;
}

/* from 表单样式 */
.el-dialog {
  width: 800px;
  /* 自定义宽度 */
  max-width: 90%;
  /* 保持最大宽度限制，可选 */
  margin-top: 10vh !important;
  /* 调整垂直位置，使对话框居中显示，！important用于覆盖可能的默认样式 */
}

/* 如果需要调整对话框内容区域的大小，可以添加如下样式 */
.el-dialog__body {
  padding: 20px 50px;
  /* 可根据需要调整内边距 */
}

.el-dialog__footer {
  text-align: center;
  /* 按钮居中对齐 */
  /* display: flex; */
  justify-content: center;
  /* 适用于弹性布局，确保按钮在水平方向上居中 */
  align-items: center;
  /* 垂直居中，如果只需要水平居中，这行可以省略 */
  height: 90px;
  /* 自定义底部高度，根据需要调整 */
  /* padding-bottom: 30; 移除默认的内边距，如果有需要的话 */
}

/* 表格表头样式 */
.el-table th .cell {
  white-space: nowrap;
  overflow: visible;
}

.operation-buttons {
  display: flex;
  gap: 8px;
  white-space: nowrap;
}
</style>
